import { message } from 'antd';
import { list, create, edit, dele } from '../services/dormitory';

export default {
  namespace: 'dormitory',

  state: {
    data: [],
    total: 0,
    success: true,
    names: [], // 存放所有的名称, 用于检测是否重名, 防止重复添加
  },

  effects: {
    *list({ payload }, { call, put }) {
      const response = yield call(list, payload);
      yield put({ type: 'callbackList', response });
    },
    *create({ payload }, { call, put }) {
      const response = yield call(create, payload);
      yield put({ type: 'callbackSave', response });
    },
    *edit({ payload }, { call, put }) {
      const response = yield call(edit, payload);
      yield put({ type: 'callbackSave', response });
    },
    *dele({ payload }, { call, put }) {
      const response = yield call(dele, payload);
      yield put({ type: 'callbackSave', response });
    },
  },

  reducers: {
    callbackList(st, { response }) {
      const state = st;
      if (response.success) {
        state.data = response.root.sort((a, b) => a.id - b.id);
        state.total = response.total;

        state.names = [];
        for (let i = 0; i < state.data.length; i += 1) {
          const item = state.data[i];
          const { name } = item;
          state.names.push(name);
        }
      }
      return { ...state };
    },
    callbackSave(st, { response }) {
      const state = st;
      state.success = response.success;
      if (response.success) message.success(response.msg);
      return { ...state };
    },
  },
};
